#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <cassert>


using namespace std;

int main() {
    int pipefd[2];
    int ret = pipe(pipefd);
    assert(ret == 0);

    pid_t pid = fork();

    if (pid == 0) {
        // 子进程：不断写入
        close(pipefd[0]); // 子进程不读


        while (true) {
            char buff[] = "Hello pipe!";
            ssize_t w = write(pipefd[1], buff, strlen(buff));
            if (w == -1) {
                perror("子进程写入失败");
                
            } else {
                cout << "子进程写入成功: " << buff << endl;
            }
            sleep(1);
        }

        close(pipefd[1]); // 清理写端
        exit(0);
    } else {
        // 父进程：读取5次后关闭读端
        close(pipefd[1]); // 父进程不写

        char buff[64];
        int cnt = 1;
        while (true) {
            int n = read(pipefd[0], buff, sizeof(buff) - 1);
            if (n > 0) {
                buff[n] = '\0';
                cout << "父进程成功读取到信息: " << buff << endl;
            } else if (n == 0) {
                cout << "写端已关闭，读取数据量为: " << n << " 字节" << endl;
                
            } else {
                perror("父进程读取失败");
                break;
            }

            if (cnt++ == 5) {
                cout << "父进程已读取5次，关闭读端" << endl;
                break;
            }

            sleep(1);
        }

        close(pipefd[0]); // 关闭读端

        // 等待子进程退出
        int status = 0;
        waitpid(pid, &status, 0);
        if (status & 0x7F) {
            printf("子进程异常退出，core dump: %d   退出信号：%d\n",
                   (status >> 7) & 1, status & 0x7F);
        } else {
            printf("子进程正常退出，退出码: %d\n", (status >> 8) & 0xFF);
        }
    }

    return 0;
}

